using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using net_work.Common.Request;
using net_work.Common.Result;
using net_work.Data.DTO.Sys;
using net_work.IService.Sys;

namespace net_work.Controllers.Sys;

[Route("api/[controller]")]
[ApiController]
public class DepartmentController(ILogger<DepartmentController> logger, IDepartmentService departmentService)
    : ControllerBase
{
    /// <summary>
    /// 获取部门列表
    /// </summary>
    /// <param name="request">分页请求实体</param>
    /// <returns>操作结果</returns>
    [HttpPost("list")]
    [Authorize]
    public async Task<IActionResult> ListDepartments([FromBody] PagedRequest request)
    {
        logger.LogInformation("获取部门列表");
        var result = await departmentService.GetDepartmentsPagedAsync(request);
        return AjaxResult.Success(result);
    }

    /// <summary>
    /// 获取部门信息
    /// </summary>
    /// <param name="departmentId">部门ID</param>
    /// <returns>操作结果</returns>
    [HttpGet("get")]
    [Authorize]
    public async Task<IActionResult> GetDepartmentById([FromQuery] long departmentId)
    {
        logger.LogInformation("获取部门信息");
        return await departmentService.SelectByIdAsync(departmentId) is { } department
            ? AjaxResult.Success(department)
            : AjaxResult.Error();
    }

    /// <summary>
    /// 新增部门
    /// </summary>
    /// <param name="departmentAddRequest">新增部门实体</param>
    /// <returns>操作结果</returns>
    [HttpPost("add")]
    [Authorize(Roles = "ADMIN,SECRET")]
    public async Task<IActionResult> AddDepartment([FromBody] DepartmentAddRequest departmentAddRequest)
    {
        logger.LogInformation("新增部门");
        var departmentId = await departmentService.InsertDepartment(departmentAddRequest);
        return departmentId > 0
            ? AjaxResult.Success(new { departmentId })
            : AjaxResult.Error();
    }

    /// <summary>
    /// 修改部门
    /// </summary>
    /// <param name="departmentUpdateRequest">修改部门实体</param>
    /// <returns>操作结果</returns>
    [HttpPost("update")]
    [Authorize(Roles = "ADMIN,SECRET")]
    public async Task<IActionResult> UpdateDepartment([FromBody] DepartmentUpdateRequest departmentUpdateRequest)
    {
        logger.LogInformation("修改部门");
        return await departmentService.UpdateDepartment(departmentUpdateRequest) > 0
            ? AjaxResult.Success()
            : AjaxResult.Error();
    }

    /// <summary>
    /// 删除部门
    /// </summary>
    /// <param name="ids">部门ID</param>
    /// <returns>操作结果</returns>
    [HttpPost("delete")]
    [Authorize(Roles = "ADMIN,SECRET")]
    public async Task<IActionResult> DeleteDepartment([FromBody] List<long> ids)
    {
        logger.LogInformation("删除部门");
        return await departmentService.DeleteDepartmentByIds(ids) > 0
            ? AjaxResult.Success()
            : AjaxResult.Error();
    }
}